package org.foreveross.que.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.dbunit.util.Base64;
import org.foreveross.que.infra.base.constant.SysConstants;
import org.json.JSONException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Controller;
//import sun.net.ftp.FtpClient;
//import sun.net.TelnetOutputStream;


import org.foreveross.que.vo.IndexVo;

@Controller
@org.springframework.context.annotation.Scope("prototype")
@Namespace("/kindEditor")
@ParentPackage("json-default")
@SuppressWarnings({ "unchecked", "rawtypes", "serial" })
public class ImportImgBaseAction extends BaseAction {
	
	
	private static final String UPLOAD_IMAGES_URL_DEFAULT = "/images/attached/";
	Logger log = Logger.getLogger(ImportImgBaseAction.class);
	private static final String IMG_REGEX = "<img src=\"(data:image/(\\w{3,4});base64,([^\"]+))\"[^>]*/>";

	private static HashMap<String, String> extMap = new HashMap<String, String>();
	static{
// 定义允许上传的文件扩展名
		extMap.put("image", "gif,jpg,jpeg,png,bmp");
		// extMap.put("flash", "swf,flv");
		// extMap.put("media",
		// "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
		// extMap.put("file",
		// "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
	}
	// protected static Pattern imgPat =
	// Pattern.compile(IMG_P,Pattern.CASE_INSENSITIVE);

	File imgFile;// 属性名为kindEditor上传文件名

	String dir;

	public String localUrl;

	protected String content;

	Map result = new HashMap();

	@Action(value = "uploadImg", results = { @Result(name = "JSON", type = "json", params = {
			"root", "result" }) })
	public String uploadImg() throws Exception {
		result = this.upload();
		return "JSON";
	}
	

	/**
	 * kindEditor上传方法
	 * 
	 * @return
	 * @throws Exception
	 */

	public Map upload() throws Exception {

		Map<String, String> params = new HashMap<String, String>();
		Map result = null;
		try {
			if (imgFile == null || imgFile.length() == 0) {
				return this.getError("请选择文件。");
			}
			result = this.loadUrlParams(params);
			if(result==null){
				result = loadNewFileName(params,localUrl, getDirName());
			}
			if (imgFile.length() > SysConstants.UPLOAD_IMG_MAX_SIZE) {
				result = getError("上传文件大小超过限制。");
			}
			if (result == null) {
				String savePath = params.get("savePath");
				String saveUrl = params.get("saveUrl");
				String newFileName = params.get("newFileName");
				result = uploadSaveFile(savePath, saveUrl, newFileName);
			}
			
		} catch (Exception e) {
			result = getError("上传文件失败。");
		} finally {
			imgFile.delete();
		}
		return result;
	}

/**
 * 加载上传初始参数	
 * @param params
 * @return
 * @throws Exception
 */
	private Map loadUrlParams(Map params) throws Exception {
		Map result = null;
		String savePath = null;
		String saveUrl = null;
//		String newFileName = null;
		
		if(StringUtils.isBlank(SysConstants.UPLOAD_IMAGES_URL)){
			savePath = this.getRequest().getRealPath(UPLOAD_IMAGES_URL_DEFAULT);
			// 文件保存目录URL
			saveUrl = this.getRequest().getContextPath() + UPLOAD_IMAGES_URL_DEFAULT;
		}else{
			savePath = SysConstants.UPLOAD_IMAGES_URL;
			// 文件保存目录URL
			saveUrl = this.getRequest().getContextPath() + SysConstants.UPLOAD_IMAGES_URL;
		}
		
		// 检查目录
		File uploadDir = new File(savePath);
		if (!uploadDir.isDirectory()) {
			result = getError("上传目录不存在。");
		}
		if (!uploadDir.canWrite()) {
			result = getError("上传目录没有写权限。");
		}
		String dirName = getDirName();
		if (!extMap.containsKey(dirName)) {
			result = getError("目录名不正确。");
		}

		// 创建文件夹
		savePath += "/" + dirName + "/";
		saveUrl += "/" + dirName + "/";
		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		savePath += ymd + "/";
		saveUrl += ymd + "/";
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		
//		String fileName = localUrl;

		
		if (result == null) {
			params.put("savePath", savePath);
			params.put("saveUrl", saveUrl);
		}
		return result;
	}

private String getDirName() {
	String dirName = dir;
	if (dirName == null) {
		dirName = "image";
	}
	return dirName;
}

private Map loadNewFileName(Map params,String fileName, String dirName)
		throws JSONException {
	Map result = null;
	String newFileName;
	// 检查扩展名
	String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1)
			.toLowerCase();
	if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(
			fileExt)) {
		result = getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName)
				+ "格式。");
	}

	SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
	newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000)
			+ "." + fileExt;
	params.put("newFileName", newFileName);
	return result;
}

	/**
	 * 保存上传文件
	 * @param savePath
	 * @param saveUrl
	 * @param newFileName
	 * @return
	 * @throws JSONException
	 */
	private Map uploadSaveFile(String savePath, String saveUrl,
			String newFileName) throws JSONException {
		try {
			File savefile = new File(new File(savePath), newFileName);
			if (!savefile.getParentFile().exists())
				savefile.getParentFile().mkdirs();
			FileUtils.copyFile(imgFile, savefile);
			Map obj = new HashMap();
			obj.put("error", 0);
			obj.put("url", saveUrl + newFileName);
			return obj;
		} catch (Exception e) {
			return getError("上传文件失败。");
		}
	}

	/**
	 * 在输入文本的img转化，并返回解析后的字符串
	 * 
	 * @param content
	 * @return
	 */
	protected String contentDecrypt(String content) throws Exception {
	
		FileInputStream fis = null;
		FileOutputStream fos = null;
		Map<String, String> params = new HashMap<String, String>();
		
		Pattern imgPat = Pattern.compile(IMG_REGEX, Pattern.CASE_INSENSITIVE);
		Matcher m = imgPat.matcher(content);
		Integer i = 1;
		Map bool = null;
		while (m.find()) {
			try{
			// 建立文件上传流
		//	 fis = new FileInputStream(m.group(1));
			if(params.isEmpty()){
				bool = this.loadUrlParams(params);
			}
			if(bool==null){
				this.loadNewFileName(params, "."+m.group(2), this.getDirName());
				String savePath = params.get("savePath");
				String saveUrl = params.get("saveUrl");
				String newFileName = params.get("newFileName");
				if(StringUtils.isNotBlank(newFileName)){
					newFileName = newFileName.substring(0, newFileName.indexOf(".")) + "_" +i+ "."+m.group(2);
					i++;
				}
				 fos = new FileOutputStream(savePath+"/"+newFileName);
				byte[] buffer = Base64.decode(m.group(3));
				int len = buffer.length;
				fos.write(buffer,0,len);
				fos.flush();
//				while ((len = fis.read(buffer)) > 0) {
//					fos.write(buffer, 0, len);
//				}
				content = StringUtils.replace(content, m.group(1), saveUrl+"/"+newFileName);
			}
			}catch(Exception e){
				e.printStackTrace();
				log.error(e);
			}finally{
				if(fis!=null){
				fis.close();
				}
				if(fos!=null){
				fos.close();
				}
			}
		}
		return content;
		
	}
	
//	public static boolean uploadFileBySun(
//			StringBuffer fileContent,
//			String host,
//			String port,
//			String userName,
//			String userPassword,
//			String path,
//			String saveFileName) { 
//
//        FtpClient ftpClient = null; 
//
//        try { 
//        	ftpClient new FtpClient(host,port);
//
//               //打开ftp服务器 
//
//            
//
//               //使用指定用户登录 
//
//              ftpClient.login(userName, userPassword); 
//
//               //转到指定路径 
//
//                ftpClient.cd(path);
//                ftpClient.binary();
//                TelnetOutputStream telOut = ftpClient.put(saveFileName);
//                
//                telOut.write(arg0, arg1, arg2)
//
//               TelnetOutputStream os = null; 
//
//
//             
//
//            //   bw.write(fileContent.toString()); 
//
//                bw.flush(); 
//
//               bw.close(); 
//
//     } catch (Exception e) { 
//
//              System.out.println(e.getMessage()); 
//
//               return false; 
//
//        } finally { 
//
//                try { 
//
//                      //关闭ftp连接 
//
//                       ftpClient.closeServer(); 
//
//               } catch (Exception e) { 
//
//                        e.printStackTrace(); 
//
//               } 
//
//       } 
//
//        return true; 
//
// }


	
	

	// public String

	private Map getError(String message) throws JSONException {
		Map obj = new HashMap();
		obj.put("error", 1);
		obj.put("message", message);
		return obj;
	}
	

	public File getImgFile() {
		return imgFile;
	}

	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public Map getResult() {
		return result;
	}

	public void setResult(Map result) {
		this.result = result;
	}

	public String getLocalUrl() {
		return localUrl;
	}

	public void setLocalUrl(String localUrl) {
		this.localUrl = localUrl;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}
	
//	protected List<String> loadRoleMenus() throws Exception{
//		this.getRoles().keySet();
//		return null;
//	}

}
